package net.pws.oos.web.stats;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.pws.common.util.DateUtils;

import org.apache.commons.lang.StringUtils;

@SuppressWarnings("rawtypes")
public class UserStats {

	private static final String UNKOWN_COUNTY = "未知区县";

	private static final String TOTAL_COUNTY = "合计（自然天）";

	private CountyStats totalStats = new CountyStats();

	private Map<String, CountyStats> statses = new HashMap<String, CountyStats>();

	public void add(Map task) {
		if (task == null) {
			return;
		}

		String date = DateUtils.getDateStr((Date) task.get("locateDate"));
		String city = (String) task.get("locationCity");
		String county = (String) task.get("locationCounty");
		if (StringUtils.isBlank(city) || StringUtils.isBlank(county)) {
			county = UNKOWN_COUNTY;
		} else {
			county = city + county;
		}

		get(county).add(date);
		totalStats.add(date);
	}

	private CountyStats get(String county) {
		if (statses.containsKey(county)) {
			return statses.get(county);
		}
		CountyStats stats = new CountyStats();
		statses.put(county, stats);
		return stats;
	}

	public List<TaskStats> toStats() {
		List<TaskStats> list = new ArrayList<TaskStats>(statses.size() + 1);
		for (String county : statses.keySet()) {
			list.add(toStats(county, statses.get(county)));
		}
		list.add(toStats(TOTAL_COUNTY, totalStats));
		return list;
	}

	private TaskStats toStats(String county, CountyStats countyStats) {
		TaskStats taskStats = new TaskStats();
		taskStats.setCounty(county);
		taskStats.setTaskCount(countyStats.getTaskCount());
		taskStats.setDateCount(countyStats.getDateCount());
		return taskStats;
	}
}
